package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.common.TArea;
import com.example.chcrm.entity.employee.RoleModels;
import com.example.chcrm.mapper.TAreaMapper;
import com.example.chcrm.service.TAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 邹
 * @Date 2025/4/23 0:58
 * @Version 1.0
 */
@Service
public class TAreaServiceImpl<T> implements TAreaService<T> {
    @Autowired
    TAreaMapper tAreaMapper;

    @Override
    public ResponseMsg<IPage<TArea>> pageList(TArea roleModels) {
        // 动态条件构建
        QueryWrapper<TArea> queryWrapper = new QueryWrapper<>();

        // 角色名称模糊查询
        if (StringUtils.isNotBlank(roleModels.getName())) {
            queryWrapper.like("name", roleModels.getName());
        }
        // 状态筛选
        if (StringUtils.isNotBlank(roleModels.getLevel())) {
            queryWrapper.eq("level", roleModels.getLevel());
        }
        // 基础条件
        queryWrapper
                .eq("is_deleted", 0)  // 未删除数据
                .orderByDesc("create_time");

        // 检查传入的department.getPage()和getRows()值
        // 执行分页查询
        List<TArea> list = tAreaMapper.selectList(queryWrapper);
//        int count  = tAreaMapper.total(roleModels);
        ResponseMsg<IPage<TArea>> iPageResponseMsg = new ResponseMsg<>();
        Page<TArea> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(roleModels.getRows());
        page.setCurrent(roleModels.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> add(TArea tArea) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //验证区域编码是否存在
        int codeCount = tAreaMapper.selectCount(new QueryWrapper<TArea>()
                .eq("id", tArea.getAdCode()).eq("is_deleted",0)).intValue();
        if (codeCount > 0) {
            msg.fail("添加失败，区域编码不能重复");
            return msg;
        }
        //验证上级是否存在
        if(!tArea.getLevel().equals("province")){
            TArea parentArea = tAreaMapper.selectById(tArea.getParentCode());
            if(parentArea == null){
                msg.fail("添加失败,上级区域不存在");
                return msg;
            }
            tArea.setParentCodeLis(parentArea.getParentCodeLis()+"/"+tArea.getAdCode());
            tArea.setParentNameLis(parentArea.getParentNameLis()+"/"+tArea.getName());
        }
        tArea.setCreateTime(new Date());
        tAreaMapper.insert(tArea);
        msg.success("添加成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> update(TArea tArea) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //验证区域是否存在
        String oldName = null;
        TArea oldTArea = tAreaMapper.selectById(tArea.getAdCode());
        if (oldTArea == null) {
            msg.fail("修改失败,区域未找到");
            return msg;
        }
        oldName = oldTArea.getName();
        //验证标识是否存在
        /*int idenCount = tAreaMapper.selectCount(new QueryWrapper<TArea>()
                .eq("identification", tArea.getIdentification())
                .ne("id", tArea.getAdCode()));
        if (idenCount > 0) {
            msg.fail("修改失败,标识已存在");
            return msg;
        }*/
        String parentNameLis = oldTArea.getParentNameLis().replace(oldTArea.getName(), tArea.getName());
        oldTArea.setParentNameLis(parentNameLis);
        oldTArea.setName(tArea.getName());
        oldTArea.setIdentification(tArea.getIdentification());
        oldTArea.setCenter(tArea.getCenter());
        tAreaMapper.updateById(oldTArea);
        //修改下级数据
        if(!oldTArea.getLevel().equals("district")){
            tAreaMapper.updateLowerNameParent(oldName+"/",tArea.getName()+"/",oldTArea.getAdCode()+"/");
        }
        msg.success("修改成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> delete(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        TArea oldTArea = tAreaMapper.selectById(id);
        if (oldTArea == null) {
            msg.fail("删除失败,区域未找到");
            return msg;
        }
//        if(!oldTArea.getLevel().equals("district")){
//            int num1 = tAreaMapper.selectCount(new QueryWrapper<TArea>()
//                    .eq("parent_code_lis", oldTArea.getAdCode()+"/"));
//            if(num1 > 0){
//                msg.fail("删除失败,区域正在使用中");
//                return msg;
//            }
//        }
        //验证区域是否使用中
//        int num = lineConfigMapper.selectCount(new QueryWrapper<LineConfig>()
//                .and(wrapper -> wrapper.eq("start_address_id", id).or().eq("end_address_id", id)));
//        if(num > 0){
//            msg.fail("删除失败,区域正在使用中");
//            return msg;
//        }
        tAreaMapper.update(null,new UpdateWrapper<TArea>().set("is_deleted",-1).eq("name",oldTArea.getName()));
        msg.success("删除成功");
        return msg;
    }

    /**
     * 查询二级省、市地址
     * @return
     */
    @Override
    public List<Map<String, Object>> getSecondLevelArea(String level) {
        List<Map<String, Object>> provincesInfo = tAreaMapper.getAreaName("province");
        if(!level.equals("province")){
            List<Map<String, Object>> cityInfo = tAreaMapper.getAreaName("city");
            for (Map<String, Object> pMap : provincesInfo) {
                List<Map<String, Object>> listPro = new ArrayList<Map<String,Object>>();
                for (Map<String, Object> cMap : cityInfo) {
                    if (cMap.get("parent_code").toString().equals(pMap.get("id").toString())) {
                        listPro.add(cMap);
                    }
                }
                pMap.put("children", listPro);// 市级所属的省级
            }
        }
        return provincesInfo;
    }
}
